package com.scisoft.scan.control.delivery;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.util.DisplayMetrics;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.scisoft.scan.data.delivery.CustomerDeliveryBean;
import com.scisoft.scan.data.delivery.DeliveryOrderBean;
import com.scisoft.scan.dy.R;
import com.scisoft.scan.control.ClearEditText;
import com.scisoft.scan.control.CommonAdapter;
import com.scisoft.scan.control.CommonViewHolder;
import com.scisoft.scan.data.delivery.DeliveryQueryPageBean;
import com.scisoft.scan.control.MainMenuActivity;
import com.scisoft.scan.data.delivery.DeliveryBean;
import com.scisoft.scan.util.CommonUtil;
import com.scisoft.scan.ws.WebServiceHelper_Delivery;

import java.util.ArrayList;
import java.util.List;

import static com.scisoft.scan.control.CommonAdapter.LOADING_END;
import static com.scisoft.scan.control.CommonAdapter.LOADING_MORE;
import static com.scisoft.scan.control.CommonAdapter.PULLUP_LOAD_MORE;

public class DeliveryActivity extends Activity {
    private ImageView iv_Back; //返回按钮
    private ImageView iv_query; //搜索按钮
    private TextView bt_undo;
    private TextView bt_done;
    private TextView bt_in;
    private View v_undo;
    private View v_done;
    private View v_in;
    private ClearEditText et_bar;
    private String bizId;// 1 未发 2 发运中 3 已发运

    //分页配置表
    private DeliveryQueryPageBean pageBean = null;
    private int currentPage = 0;
    float lastY = 0;
    //货架分页显示控件
    DeliveryOrderAdapter deliveryOrderAdapter;
    private SwipeRefreshLayout mRefreshLayout;
    private RecyclerView mRecyclerView;
    private LinearLayoutManager mLayoutManager;
    private int lastVisibleItem; //最后一个可见Item的位置，关键所在

    @Override
    @SuppressLint("ClickableViewAccessibility")
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_delivery);

        //控件初始化
        bt_undo = findViewById(R.id.bt_undo);
        bt_done = findViewById(R.id.bt_done);
        bt_in = findViewById(R.id.bt_in);
        v_undo = findViewById(R.id.v_undo);
        v_done = findViewById(R.id.v_done);
        v_in = findViewById(R.id.v_in);
        et_bar = findViewById(R.id.et_bar);
        et_bar.setText("");
        //页签切换
        bt_undo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_in.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        bt_done.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setButton(v);
            }
        });
        //返回
        iv_Back = findViewById(R.id.iv_back);
        iv_Back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(DeliveryActivity.this, MainMenuActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
        //搜索框
        iv_query = findViewById(R.id.iv_query);
        iv_query.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                QueryDeliveryOrder(true);
            }
        });
        //数据
        mRefreshLayout = findViewById(R.id.swipe_layout);
        mRefreshLayout.setProgressViewEndTarget(true, 0);
        mRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                mRefreshLayout.setRefreshing(false);
                QueryDeliveryOrder(true);
            }
        });
        mRecyclerView = findViewById(R.id.lv_data);
        deliveryOrderAdapter = new DeliveryOrderAdapter(DeliveryActivity.this);
        DisplayMetrics displayMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
        int fullWidth = displayMetrics.widthPixels;
        deliveryOrderAdapter.setItemLayout(R.layout.item_delivery, R.id.hsv, R.id.layout_show, R.id.layout_hide, fullWidth);
        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        deliveryOrderAdapter.setOnItemClickListener(new DeliveryOrderAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                DeliveryBean deliveryBean = deliveryOrderAdapter.getItemData(position);
                if (deliveryBean != null) {
                    if("1".equals(bizId)){
                        //未发运要判断是否可以合并发运
                        CommonUtil.showPress(DeliveryActivity.this);
                        QueryCustomerDeliveryTask queryCustomerDeliveryTask = new QueryCustomerDeliveryTask(DeliveryActivity.this, deliveryBean);
                        queryCustomerDeliveryTask.execute();
                    }else{
                        //直接跳转
                        Intent intent = new Intent(DeliveryActivity.this, DeliveryOrderActivity.class);
                        intent.putExtra("data", deliveryBean);
                        intent.putExtra("flag", bizId);
                        startActivity(intent);
                    }

                }
            }
        });
        //滚动的时候清空左滑按钮
        mRecyclerView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                switch (event.getAction()) {
                    case MotionEvent.ACTION_UP:
                        if (Math.abs(event.getY() - lastY) > 5)
                            deliveryOrderAdapter.clearLeftMenuList();
                }
                return false;
            }
        });
        mRecyclerView.setAdapter(deliveryOrderAdapter);
        //设置滑动监听
        mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                //判断是否滑动到底
                if (newState == RecyclerView.SCROLL_STATE_IDLE && lastVisibleItem + 1 == deliveryOrderAdapter.getItemCount()) {
                    //滑动到底，需要改变状态为 上拉加载更多
                    deliveryOrderAdapter.changeMoreStatus(LOADING_MORE);
                    QueryDeliveryOrder(false);
                } else {
                    deliveryOrderAdapter.changeMoreStatus(PULLUP_LOAD_MORE);
                }
            }

            //更新最后可见位置
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                lastVisibleItem = mLayoutManager.findLastVisibleItemPosition();

            }
        });

        setButton(bt_undo);

    }

    //设置tab页的颜色
    private void setButton(View v) {
        if (v.getId() == bt_undo.getId()) {
            bizId = "1";//未处理
            v_undo.setVisibility(View.VISIBLE);
            v_in.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_in.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else if (v.getId() == bt_in.getId()) {
            bizId = "2";//处理中
            v_undo.setVisibility(View.INVISIBLE);
            v_in.setVisibility(View.VISIBLE);
            v_done.setVisibility(View.INVISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_in.setTextColor(getResources().getColor(R.color.tab_text_color_select));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
        } else {
            bizId = "3";//已完成
            v_undo.setVisibility(View.INVISIBLE);
            v_in.setVisibility(View.INVISIBLE);
            v_done.setVisibility(View.VISIBLE);
            bt_undo.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_in.setTextColor(getResources().getColor(R.color.tab_text_color_unselect));
            bt_done.setTextColor(getResources().getColor(R.color.tab_text_color_select));
        }
        QueryDeliveryOrder(true);
    }

    //查询订单
    private void QueryDeliveryOrder(boolean refresh) {
        CommonUtil.showPress(DeliveryActivity.this);
        QueryDeliveryTask queryDeliveryTask = new QueryDeliveryTask(DeliveryActivity.this, refresh);
        queryDeliveryTask.execute();
    }

    //绑定数据
    @SuppressLint("SetTextI18n")
    private void BindData(Context context, List<DeliveryBean> newData, boolean refresh) {
        //统计
        bt_undo.setText("未发运（" + String.valueOf(pageBean.notCount) + "）");
        bt_in.setText("发运中（" + String.valueOf(pageBean.inCount) + "）");
        bt_done.setText("已发运（" + String.valueOf(pageBean.okCount) + "）");
        //适配器
        deliveryOrderAdapter.clearLeftMenuList();
        if (!refresh) {
            //数据
            if (newData.size() > 0) {
                deliveryOrderAdapter.addMoreItem(newData);
            } else {
                deliveryOrderAdapter.changeMoreStatus(LOADING_END);
            }
        } else {
            if (newData.size() > 0) {
                deliveryOrderAdapter.clearAddItem(newData);
            } else {
                deliveryOrderAdapter.clearAddItem(newData);
                deliveryOrderAdapter.changeMoreStatus(LOADING_END);
            }
        }
    }

    //查询订单服务
    class QueryDeliveryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        boolean mrefresh = true;
        private String msg = "";
        private List<DeliveryBean> newData = new ArrayList<>();

        QueryDeliveryTask(Context context, boolean refresh) {
            super();
            mcontext = context;
            mrefresh = refresh;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            //查询
            try {
                //重新刷新
                if (mrefresh) {
                    pageBean = null;
                }
                //第一次程序时需要先查询分页信息
                if (pageBean == null) {
                    pageBean = WebServiceHelper_Delivery.DELIVERY_01(bizId, et_bar.getUpperText().toString());
                    currentPage = 0;
                }
                //翻页
                currentPage++;
                //判断是否全部显示，如果没有就查询下一页
                if (currentPage <= pageBean.pageCount) {
                    newData = WebServiceHelper_Delivery.DELIVERY_02(bizId, et_bar.getUpperText().toString(), pageBean.pageSize, currentPage);
                }
                //超过最大页则返回
                if (currentPage > pageBean.pageCount) {
                    currentPage = pageBean.pageCount;
                }
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, mrefresh);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //查询客户已发运订单服务
    class QueryCustomerDeliveryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private DeliveryBean mdeliveryBean;
        private String msg = "";
        private List<CustomerDeliveryBean> customerDeliveryBeanList = new ArrayList<>();

        QueryCustomerDeliveryTask(Context context, DeliveryBean deliveryBean) {
            super();
            mcontext = context;
            mdeliveryBean = deliveryBean;
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                customerDeliveryBeanList = WebServiceHelper_Delivery.DELIVERY_14(mdeliveryBean.orderId);
                msg = "成功";
            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                if (customerDeliveryBeanList == null || customerDeliveryBeanList.size() == 0) {
                    //直接跳转
                    Intent intent = new Intent(DeliveryActivity.this, DeliveryOrderActivity.class);
                    intent.putExtra("data", mdeliveryBean);
                    intent.putExtra("flag", bizId);
                    startActivity(intent);
                } else {
                    //弹窗让用户选择
                    selectDeliveryOrder(customerDeliveryBeanList, mdeliveryBean);
                }
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //选择或者取消选择订单服务
    class DeleteDeliveryTask extends AsyncTask<String, Integer, String> {
        private Context mcontext;
        private String msg = "";
        private String deliveryId;
        private List<DeliveryBean> newData = new ArrayList<>();

        DeleteDeliveryTask(Context context, String deliveryId) {
            super();
            mcontext = context;
            this.deliveryId = deliveryId;
        }

        @Override
        protected String doInBackground(String... params) {
            //查询
            try {
                msg = WebServiceHelper_Delivery.DELIVERY_17(deliveryId);
                //查询列表数据
                if (msg.contains("成功")) {
                    //第一次程序时需要先查询分页信息
                    pageBean = WebServiceHelper_Delivery.DELIVERY_01(bizId, et_bar.getUpperText().toString());
                    currentPage = 0;
                    //翻页
                    currentPage++;
                    //判断是否全部显示，如果没有就查询下一页
                    if (currentPage <= pageBean.pageCount) {
                        newData = WebServiceHelper_Delivery.DELIVERY_02(bizId, et_bar.getUpperText().toString(), pageBean.pageSize, currentPage);
                    }
                    //超过最大页则返回
                    if (currentPage > pageBean.pageCount) {
                        currentPage = pageBean.pageCount;
                    }
                    msg = "成功";
                }

            } catch (Exception e) {
                msg = e.getMessage();
                e.printStackTrace();
            }
            //将结果返回给onPostExecute方法
            return msg;
        }

        @Override
        //此方法可以在主线程改变UI
        protected void onPostExecute(String result) {
            CommonUtil.hidePress();
            if (msg.contains("成功")) {
                BindData(mcontext, newData, true);
            } else {
                Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
            }
        }
    }

    //弹出选择发运单窗口
    private void selectDeliveryOrder(final List<CustomerDeliveryBean> customerDeliveryBean,final DeliveryBean deliveryBean ) {
        //1.创建一个Dialog对象,去除标题栏
        final Dialog mDialog = new Dialog(this);
        mDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        //2.填充布局,将自定义布局设置进去
        LayoutInflater inflater = LayoutInflater.from(this);
        View dialogView = inflater.inflate(R.layout.dialog_delivery_order, null);
        mDialog.setContentView(dialogView);
        //3.设置指定的宽高,如果不设置的话，弹出的对话框可能不会显示全整个布局，当然在布局中写死宽高也可以
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
        Window window = mDialog.getWindow();
        lp.copyFrom(window.getAttributes());
        lp.width = WindowManager.LayoutParams.WRAP_CONTENT;
        lp.height = WindowManager.LayoutParams.WRAP_CONTENT;
        //注意要在Dialog show之后，再将宽高属性设置进去，才有效果
        mDialog.show();
        window.setAttributes(lp);
        //4、设置点击其它地方不让消失弹窗
        mDialog.setCancelable(false);
        //5、初始化控件
        ListView lv_data = dialogView.findViewById(R.id.lv_data);
        lv_data.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >= 0 && position < customerDeliveryBean.size()) {
                    CustomerDeliveryBean depotOrderBean = customerDeliveryBean.get(position);
                    Intent intent = new Intent(DeliveryActivity.this, DeliveryOrderActivity.class);
                    DeliveryBean temp = deliveryBean;
                    temp.deliveryId = depotOrderBean.deliveryId;//替换编号
                    intent.putExtra("data", temp);
                    intent.putExtra("flag", bizId);
                    startActivity(intent);
                }
            }
        });
        DeliverySelectOrderAdapter adapter = new DeliverySelectOrderAdapter(customerDeliveryBean, this);
        lv_data.setAdapter(adapter);


        TextView tv_ok = dialogView.findViewById(R.id.tv_ok);
        tv_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //提交
                Intent intent = new Intent(DeliveryActivity.this, DeliveryOrderActivity.class);
                intent.putExtra("data", deliveryBean);
                intent.putExtra("flag", bizId);
                startActivity(intent);
                mDialog.dismiss();
            }
        });
        TextView tv_cancel = dialogView.findViewById(R.id.tv_cancel);
        tv_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDialog.dismiss();
            }
        });
    }

    //订单适配器相关功能
    class DeliveryOrderAdapter extends CommonAdapter<DeliveryBean> {

        //构造函数
        public DeliveryOrderAdapter(Context context) {
            super(context);
        }

        @Override
        public void convert(CommonViewHolder holder, final DeliveryBean deliveryBean, int position) {
            TextView tv_customer = holder.getView(R.id.tv_customer);
            TextView tv_contact = holder.getView(R.id.tv_contact);
            TextView tv_orderNo = holder.getView(R.id.tv_orderNo);
            TextView tv_orderType = holder.getView(R.id.tv_orderType);
            TextView tv_depotName = holder.getView(R.id.tv_depotName);
            TextView tv_address = holder.getView(R.id.tv_address);
            TextView tv_statis = holder.getView(R.id.tv_statis);

            //获取相应索引的ItemBean对象
            final DeliveryBean bean = mList.get(position);
            //设置控件的对应属性值
            tv_customer.setText(bean.customer);
            if (bean.telephone != null && bean.telephone.length() > 0) {
                tv_contact.setText(bean.contact + " （ " + bean.telephone + " ）");
            } else {
                tv_contact.setText(bean.contact);
            }
            tv_orderNo.setText(bean.orderNo);
            tv_orderType.setText(bean.orderType);
            //颜色:急件订单红色
            if (bean.orderType != null && bean.orderType.contains("急件")) {
                tv_orderType.setTextColor(Color.parseColor("#FF0000"));
            } else {
                tv_orderType.setTextColor(Color.parseColor("#999999"));
            }
            tv_depotName.setText(bean.depotName);
            tv_address.setText(bean.address);
            tv_statis.setText(bean.detail);

            //取消(提交)
            TextView tv_ok = holder.getView(R.id.tv_ok);
            if ("2".equals(bizId)) {
                //发运中
                tv_ok.setVisibility(View.VISIBLE);
                tv_ok.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        CommonUtil.showPress(DeliveryActivity.this);
                        DeleteDeliveryTask deleteDeliveryTask = new DeleteDeliveryTask(DeliveryActivity.this, bean.deliveryId);
                        deleteDeliveryTask.execute();
                    }
                });
            } else {
                tv_ok.setVisibility(View.INVISIBLE);
            }

        }
    }

    //订单适配器
    class DeliverySelectOrderAdapter extends BaseAdapter {
        private LayoutInflater mInflater;//布局装载器对象
        private List<CustomerDeliveryBean> deliveryOrderBeanList;

        public DeliverySelectOrderAdapter(List<CustomerDeliveryBean> deliveryOrderBeanList,Context context) {
            this.deliveryOrderBeanList = deliveryOrderBeanList;
            mInflater = LayoutInflater.from(context);
        }

        @Override
        public int getCount() {
            return deliveryOrderBeanList.size();
        }

        @Override
        public Object getItem(int position) {
            return deliveryOrderBeanList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            //将布局文件转化为View对象
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_deliveryorderselect, null);
            }
            final CustomerDeliveryBean bean = deliveryOrderBeanList.get(position);
            //发运单NO
            TextView tv_title = convertView.findViewById(R.id.tv_title);
            tv_title.setText(bean.deliceryNo);
            //发运单信息
            TextView tv_info  = convertView.findViewById(R.id.tv_info);
            tv_info.setText(bean.deliveryInfo);
            return convertView;
        }
    }
}
